<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'

import {ref} from 'vue'

//图书数据模型
const books = ref('')

//图书isbn数据模型
const isbn = ref('')

//用户搜索时选中的分类id
const bookId = ref('')

//借阅人列表数据模型
const record = ref('')

//分页条数据模型
const pageNum = ref(1)  // 默认第1页
const total = ref(0)    // 默认总条数0
const pageSize = ref(10) // 默认每页10条

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  console.log(pageSize.value)
  recordList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  recordList()
}


//回显图书分类
import {
  recordsListService,
  recordsAddService,
  recordsDeleteService,
  recordsUpdateService,
  bookListService
} from '@/api/book.js'

const bookList = async () => {
  let result = await bookListService();
  books.value = result.data.records;
  
  // 提取需要的字段
  const extractedBooks = books.value.map(book => {
    return {
      bookId: book.bookId,
      bookName: book.bookName,
      isbn: book.isbn
    }
  });
  
  // 如果需要保存提取后的数据到新的响应式变量
  const bookOptions = ref(extractedBooks);
  
  console.log('提取的图书信息：', extractedBooks);
  return extractedBooks;
}

//获取图书列表数据
const recordList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  // console.log(params)
  let result = await recordsListService(params);
  console.log(result.data)

  //渲染视图
  record.value = result.data.records;
  pageNum.value = result.data.current;
  total.value = result.data.total;
  pageSize.value = result.data.size;
}


bookList()
recordList();

import {QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {Plus} from '@element-plus/icons-vue'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//借阅人数据模型
const recordModel = ref({
  recordId: '',
  bookId: '',
  bookName: '',
  isbn: '',
  borrower: '',  // 改为 borrower 以匹配后端
  borrowTime: '',
  returnTime: '',
})

// 添加表单验证规则
const recordRules = {
  bookId: [
    { required: true, message: '请选择图书', trigger: 'change' }
  ],
  borrower: [
    { required: true, message: '请输入借阅人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  borrowTime: [
    { required: true, message: '请选择借阅时间', trigger: 'change' }
  ],
  returnTime: [
    { required: true, message: '请选择归还时间', trigger: 'change' }
  ]
}

// 清空表单数据
const resetForm = () => {
  recordModel.value = {
    recordId: '',
    bookId: '',
    bookName: '',
    isbn: '',
    borrower: '',
    borrowTime: '',
    returnTime: '',
  }
}

//控制添加图书分类弹窗
const dialogVisible = ref(false)
//定义变量,控制标题的展示
const title = ref('')
//展示编辑弹窗
const showDialog = (row) => {
  dialogVisible.value = true;
  title.value = '编辑图书借阅人信息';
  //数据拷贝
  recordModel.value.bookName = row.bookName;
  recordModel.value.borrower = row.borrowerName;
  recordModel.value.isbn = row.isbn;
  recordModel.value.borrowTime = row.borrowTime;
  recordModel.value.returnTime = row.returnTime;
  recordModel.value.statusDesc = row.statusDesc;
  //扩展recordId属性,将来需要传递给后台,完成图书分类的修改
  recordModel.value.recordId = row.recordId
}
//删除图书分类
import {ElMessageBox} from 'element-plus'

const deleteRecord = (row) => {
  //提示用户  确认框

  ElMessageBox.confirm(
      '你确认要删除该图书借阅人信息吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        //调用接口
        let result = await recordsDeleteService(row.recordId);
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新列表
        recordList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '用户取消了删除',
        })
      })
}
//导入token和用户信息
import {useTokenStore} from '@/stores/token.js';
import useUserInfoStore from '@/stores/userInfo.js'

const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();

// //上传成功的回调函数
// const uploadSuccess = (result) => {
//   recordModel.value.coverImg = result.data;
//   console.log(result.data);
// }

//添加图书借阅人
import {ElMessage} from 'element-plus'

const addRecord = async () => {
  try {
    // // 表单验证
    // await recordForm.value.validate();
    
    // 调用接口
    let result = await recordsAddService(recordModel.value);

    if (result.code === 200) {
      ElMessage.success(result.msg || '添加成功');
      //让抽屉消失
      visibleDrawer.value = false;
      //重置表单
      resetForm();
      //刷新当前列表
      recordList();
    } else {
      ElMessage.error(result.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加失败:', error);
    ElMessage.error(error.response?.data?.msg || '添加失败');
  }
}


const updateRecord = async () => {
  console.log(recordModel.value)
  //调用接口
  let result = await recordsUpdateService(recordModel.value);

  ElMessage.success(result.msg ? result.msg : '修改成功')
  clearData()

  //调用获取所有图书分类的函数
  await recordList();

  //隐藏弹窗
  dialogVisible.value = false;
}

// 在script部分添加处理选择图书的方法
const handleBookSelect = (bookId) => {
  // 从books中找到选中的图书
  const selectedBook = books.value.find(book => book.bookId === bookId);
  if (selectedBook) {
    recordModel.value.bookName = selectedBook.bookName;
    recordModel.value.isbn = selectedBook.isbn;
  }
}

// 打开添加借阅弹窗时，自动设置当前用户为借阅人
const openAddDrawer = () => {
  visibleDrawer.value = true;
  // 设置当前用户为借阅人
  recordModel.value.borrower = userInfoStore.info.username;
}
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>图书借阅人管理</span>
        <div class="extra">
          <el-button type="primary" @click="openAddDrawer">添加图书借阅人</el-button>
        </div>
      </div>
    </template>
    <!-- 图书列表 -->
    <el-table :data="record" style="width: 100%">
      <el-table-column label="图书名称" prop="bookName"></el-table-column>
      <el-table-column label="图书借阅人" prop="borrower"></el-table-column>
      <el-table-column label="图书借阅时间" prop="borrowTime"></el-table-column>
      <el-table-column label="图书归还时间" prop="returnTime"></el-table-column>
      <el-table-column label="图书状态" wbookIdth="100">
        <template #default="{ row }">
          <el-tag v-if="row.statusDesc == '已归还'" type="success">已归还</el-tag>
          <el-tag v-else-if="row.statusDesc == '借阅中'" type="warning">借阅中</el-tag>
          <el-tag v-else type="danger">已逾期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" wbookIdth="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteRecord(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
    <!-- 添加借阅人弹窗 -->
    <el-drawer v-model="visibleDrawer" title="添加图书借阅记录" direction="rtl" size="50%">
      <el-form
          ref="recordForm"
          :model="recordModel"
          :rules="recordRules"
          label-width="120px"
          label-position="left"
          status-icon
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="选择图书" prop="bookId">
              <el-select 
                v-model="recordModel.bookId"
                placeholder="请选择图书"
                @change="handleBookSelect"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="book in books"
                  :key="book.bookId"
                  :label="book.bookName"
                  :value="book.bookId"
                >
                  <span>{{ book.bookName }} (ISBN: {{ book.isbn }})</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="图书名称" prop="bookName">
              <el-input
                  v-model="recordModel.bookName"
                  placeholder="请输入图书名称"
                  :disabled="true"
                  clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="图书标准ISBN编号" prop="isbn">
              <el-input
                  v-model="recordModel.isbn"
                  placeholder="13位ISBN编号"
                  :disabled="true"
                  clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="图书借阅人" prop="borrower">
              <el-input
                  v-model="recordModel.borrower"
                  placeholder="请输入借阅人姓名"
                  clearable
                  :maxlength="20"
                  show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="图书借阅时间" prop="borrowTime">
              <el-date-picker
                  v-model="recordModel.borrowTime"
                  type="datetime"
                  placeholder="选择借阅时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="图书归还时间" prop="returnTime">
              <el-date-picker
                  v-model="recordModel.returnTime"
                  type="datetime"
                  placeholder="选择归还时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="end">
          <el-col :span="6">
            <el-button type="primary" @click="addRecord">确认添加</el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="info" @click="visibleDrawer = false">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>
    <!-- 编辑借阅人弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" wbookIdth="30%">
      <el-form :model="recordModel" :rules="rules" label-wbookIdth="100px" style="padding-right: 30px">
        <el-form-item label="图书名称" prop="bookName">
          <el-input v-model="recordModel.bookName" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="图书标准ISBN编号" prop="isbn">
          <el-input v-model="recordModel.isbn" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="图书借阅人" prop="borrower">
          <el-input v-model="recordModel.borrower" minlength="1" maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="图书借阅时间" prop="borrowTime">
          <el-input v-model="recordModel.borrowTime" minlength="1" maxlength="10">
          </el-input>
        </el-form-item>
        <el-form-item label="图书归还时间" prop="returnTime">
          <el-input v-model="recordModel.returnTime" minlength="1" maxlength="10">
          </el-input>
        </el-form-item>
        <el-form-item label="图书状态" prop="status">
          <el-select v-model="recordModel.statusDesc" placeholder="请选择图书状态">
            <el-option label="借阅中" value="借阅中"></el-option>
            <el-option label="已归还" value="已归还"></el-option>
            <el-option label="已逾期" value="已逾期"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                  <el-button type="primary"
                             @click="title == '添加图书借阅人' ? addRecord() : updateRecord()"> 确认 </el-button>
                </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>